package com.gitee.wsl.compose.modifier.style

import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.layout.layout


/**
 * Rotates/transforms the composable by 90 degrees in the clockwise or anti-clockwise direction.
 *
 * @param clockwise `true` if the composable should be rotated clockwise, `false` if anti-clockwise.
 * @return A modified [Modifier] with the rotation applied.
 *
 * Usage example:
 * ```
 * Box(
 *     modifier = Modifier
 *         .fillMaxSize()
 *         .rotate(clockwise = true)
 * ) {
 *     // content here
 * }
 * ```
 *
 * @since 1.0.0
 * @author Zakir Sheikh
 */

fun Modifier.rotateTransform(
    clockwise: Boolean
): Modifier {
    val transform = Modifier.layout { measurable, constraints ->
        // as rotation is taking place
        // the height becomes so construct new set of construnts from old one.
        val newConstraints = constraints.copy(
            minWidth = constraints.minHeight,
            minHeight = constraints.minWidth,
            maxHeight = constraints.maxWidth,
            maxWidth = constraints.maxHeight
        )

        // measure measurable with new constraints.
        val placeable = measurable.measure(newConstraints)

        layout(placeable.height, placeable.width) {

            //Compute where to place the measurable.
            // TODO needs to rethink these
            val x = -(placeable.width / 2 - placeable.height / 2)
            val y = -(placeable.height / 2 - placeable.width / 2)

            placeable.place(x = x, y = y)
        }
    }

    val rotated = Modifier.rotate(if (clockwise) 90f else -90f)

    // transform and then apply rotation.
    return this
        .then(transform)
        .then(rotated)
}